<template>
  <div class="questions-choice-container">
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 新增试题按钮 -->
      <div slot="header" class="clearfix">
        <el-button style="float: right;" type="success" icon="el-icon-edit" @click="$router.push('/questions/new')">新增试题</el-button>
      </div>

      <!-- 下拉框选择区域 -->
      <el-form class="questionsSelectForm" ref="questionsSelectFormRef" label-width="90px">
        <div class="item-row">
          <!-- 学科 -->
          <div class="select-item">
            <el-form-item label="学科">
              <el-select v-model="queryData.subjectID" @change="onSubjectChange" placeholder="请选择学科">
                <el-option v-for="item in subjectOptions" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 二级目录 -->
          <div class="select-item">
            <el-form-item label="二级目录">
              <el-select v-model="queryData.catalogID" placeholder="请选择二级目录">
                <el-option v-for="item in directoryList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 标签 -->
          <div class="select-item">
            <el-form-item label="标签">
              <el-select v-model="queryData.tags" placeholder="请选择标签">
                <el-option v-for="item in tagsList" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>
          <!-- 关键字 -->
          <div class="select-item">
            <el-form-item label="关键字">
              <el-input v-model.trim="queryData.keyword" placeholder="请输入关键字"></el-input>
            </el-form-item>
          </div>
        </div>

        <div class="item-row">
          <div class="select-item">
            <el-form-item label="试题类型">
              <el-select v-model="queryData.questionType" placeholder="请选择试题类型">
                <el-option v-for="item in quesType" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="select-item">
            <el-form-item label="难度">
              <el-select v-model="queryData.difficulty" placeholder="请选择难度">
                <el-option v-for="item in quesDifficulty" :key="item.value" :label="item.label" :value="item.value"> </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="select-item">
            <el-form-item label="方向">
              <el-select v-model="queryData.direction" placeholder="请选择方向">
                <el-option v-for="item in directions" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="select-item">
            <el-form-item label="录入人">
              <el-select v-model="queryData.creatorID" placeholder="请选择录入人">
                <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </div>
        </div>

        <div class="item-row">
          <div class="select-item">
            <el-form-item label="题目备注">
              <el-input v-model.trim="queryData.remarks" placeholder="请输入题目备注"></el-input>
            </el-form-item>
          </div>

          <div class="select-item">
            <el-form-item label="企业简称">
              <el-input v-model.trim="queryData.shortName" placeholder="请输入企业简称"></el-input>
            </el-form-item>
          </div>

          <div class="select-item">
            <el-form-item label="城市" class="city-select">
              <el-select class="city" v-model="queryData.province" placeholder="请选择城市" @change="onCityChange">
                <el-option v-for="item in provinces" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
              <el-select class="city" v-model="queryData.city" placeholder="请选择城市">
                <el-option v-for="item in areas" :key="item" :label="item" :value="item"> </el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="select-item cleanAndSearch">
            <el-button @click="clean">清除</el-button>
            <el-button @click="getChoiceQuestionsList" type="primary" class="search-btn">搜索</el-button>
          </div>
        </div>
      </el-form>

      <!-- 选项卡区域 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="全部" name="null"></el-tab-pane>
        <el-tab-pane label="待审核" name="0"></el-tab-pane>
        <el-tab-pane label="已审核" name="1"></el-tab-pane>
        <el-tab-pane label="已拒绝" name="2"></el-tab-pane>
      </el-tabs>

      <!-- 精选题库数量区域 -->
      <el-alert type="info" show-icon :closable="false">
        <div slot="title">数据一共{{ total }}条</div>
      </el-alert>

      <!-- 精选题库表格区域 -->
      <el-table :data="choiceQuestionsList" style="width: 100%;">
        <el-table-column label="试题编号" prop="number" width="120"></el-table-column>
        <el-table-column label="学科" prop="subject" width="130"></el-table-column>
        <el-table-column label="目录" prop="catalog" width="130"></el-table-column>
        <el-table-column label="题型" width="130">
          <template slot-scope="scope">{{ questionTypes[scope.row.questionType] }}</template>
        </el-table-column>
        <el-table-column label="题干" width="310">
          <template slot-scope="scope"><span v-html="scope.row.question"></span></template>
        </el-table-column>
        <el-table-column label="录入时间" width="240">
          <template slot-scope="scope">{{ new Date(scope.row.addDate) | dateFormat }}</template>
        </el-table-column>
        <el-table-column label="难度" width="100">
          <template slot-scope="scope">{{ questionDifficulty[scope.row.difficulty] }}</template>
        </el-table-column>
        <el-table-column label="录入人" prop="creator" width="130"></el-table-column>
        <el-table-column label="审核状态" width="130">
          <template slot-scope="scope">
            {{ chkState[scope.row.chkState] }}
          </template>
        </el-table-column>
        <el-table-column label="审核意见" prop="chkRemarks" width="130"></el-table-column>
        <el-table-column label="审核人" prop="chkUser" width="130"></el-table-column>
        <el-table-column label="发布状态" width="130">
          <template slot-scope="scope">
            {{ pubState(scope.row.publishState, scope.row.chkState) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="230" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="quesPreview(scope.row.id)">预览</el-button>
            <el-button type="text" :disabled="scope.row.chkState !== 0" @click="checkQuestions(scope.row.id)">审核</el-button>

            <el-button type="text" :disabled="scope.row.publishState === 1" @click="$router.push('/questions/new?id=' + scope.row.id)">修改</el-button>

            <el-button type="text" @click="publishChoice(scope.row.id, scope.row.publishState)">{{ scope.row.publishState === 1 ? '下架' : '上架 ' }}</el-button>
            <el-button type="text" :disabled="scope.row.publishState === 1" @click="deleteQuestion(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <page-tool
        class="pageNation"
        :total="total"
        :paginationPage="queryData.page"
        :paginationPagesize="queryData.pagesize"
        @pageSizeChange="onpageSizeChange($event)"
        @pageChange="onpageChange($event)"
      ></page-tool>

      <!-- 试题预览弹出框 -->
      <question-preview :id="quPrev.previewId" :dialogTableVisible="quPrev.isPreviewShow" @close-dialog="quPrev.isPreviewShow = false"></question-preview>

      <!-- 试题审核弹出框 -->
      <el-dialog title="题目审核" :visible.sync="isCheckVisible" width="25%">
        <el-form :model="checkForm">
          <el-radio v-model="checkForm.chkState" label="1">通过</el-radio>
          <el-radio v-model="checkForm.chkState" label="2">拒绝</el-radio>
          <el-input type="textarea" :rows="2" placeholder="请输入审核意见" v-model.trim="checkForm.chkRemarks"> </el-input>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="isCheckVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleCheck" :plain="true">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { choiceQuestionsList } from '@/api/hmmm/questions' // 获取精选题库列表
import { getsimplesubject as simpleSucjects } from '@/api/hmmm/subjects' // 简单学科列表
import { simples as simpleDirectorys } from '@/api/hmmm/directorys' // 简单目录
import { simple as simpleTags } from '@/api/hmmm/tags' // 标签
import { list as userList } from '@/api/base/users' // 获取用户列表
import PageTool from '../components/pageTool' // 分页组件
import { questionType as qt } from '@/api/hmmm/constants' // 试题类型
import { difficulty } from '@/api/hmmm/constants' // 试题难度
import { direction } from '@/api/hmmm/constants' // 试题方向
import { provinces, citys } from '@/api/hmmm/citys' // 城市数据
import QuestionPreview from '../components/questions-preview' // 试题预览组件
import { checkQuestions, publishQuestions, deleteQuestionById } from '@/api/hmmm/questions' // 审核试题 , 上下架 , 删除题目

export default {
  name: 'ChoiceQuestions',
  components: { PageTool, QuestionPreview },
  data() {
    return {
      subjectOptions: [], // 学科简单列表
      directoryList: [], // 当前选中学科的目录列表
      tagsList: [], // 当前选中学科的标签列表

      choiceQuestionsList: [], // 精选题库数据列表
      total: 0, // 总题数
      checkForm: {
        id: '',
        chkState: '1',
        chkRemarks: ''
      },

      // 精选题库查询参数
      queryData: {
        page: 1,
        pagesize: 5,
        subjectID: null, // 学科
        catalogID: null, // 目标
        tags: null, // 标签
        keyword: null, // 关键字
        questionType: '', //试题类型
        difficulty: '', // 难度
        direction: null, // 方向
        creatorID: null, // 录入人
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        province: null,
        city: null,
        chkState: null // 审核状态
      },

      activeName: 'null',
      isCheckVisible: false, // 控制试题审核显示或隐藏

      questionTypes: { 1: '单选', 2: '多选', 3: '简答' },
      quesType: qt, // 题型下拉框绑定数组
      questionDifficulty: { 1: '简单', 2: '一般', 3: '困难' },
      quesDifficulty: difficulty, // 难度下拉框绑定数组
      directions: direction,
      userList: [], // 试题录入人
      provinces: provinces(),
      areas: [],
      chkState: { 0: '待审核', 1: '通过', 2: '拒绝' }, // 审核状态

      // 调用试题预览组件时的传值对象
      quPrev: {
        previewId: '',
        isPreviewShow: false
      }
    }
  },
  methods: {
    // 获取精选题库列表
    async getChoiceQuestionsList() {
      try {
        const { data } = await choiceQuestionsList(this.queryData)
        // console.log(data);
        this.choiceQuestionsList = data.items
        this.total = data.counts
      } catch (error) {
        this.$message.error('获取基础试题数据失败,请稍后重试')
      }
    },

    // 点击选项卡
    handleClick() {
      if (this.activeName === 'null') {
        this.queryData.chkState = null
      } else {
        this.queryData.chkState = Number(this.activeName)
      }
      this.getChoiceQuestionsList()
    },

    // 发布状态
    pubState(pub, chk) {
      if (pub === 1) {
        return '已发布'
      } else if (chk === 1) {
        return '已下架'
      } else {
        return '待发布'
      }
    },

    // 点击审核
    checkQuestions(id) {
      this.isCheckVisible = true
      this.checkForm.id = id
      console.log(this.checkForm)
    },

    // 审核试题
    async handleCheck() {
      if (this.checkForm.chkRemarks.length === 0) {
        return this.$message.info('审核意见不能为空')
      }
      try {
        this.checkForm.chkState = +this.checkForm.chkState
        const res = await checkQuestions(this.checkForm)
        console.log(res)
        this.$message.success('操作成功')
        this.getChoiceQuestionsList()
        this.isCheckVisible = false
      } catch (error) {
        this.$message.error('操作失败,请稍后重试')
      }
    },

    // 上下架
    async publishChoice(id, pubState) {
      // console.log(id, pubState);
      let msg = ''
      let publishState = 0
      if (pubState === 1) {
        msg = '你确定要下架这道题目吗?'
        publishState = 0
      } else {
        msg = '你确定要上架这道题目吗?'
        publishState = 1
      }
      const result = await this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'confirm') {
        try {
          const res = await publishQuestions({ id, publishState })
          console.log(res)
          this.$message.success('操作成功')
          this.getChoiceQuestionsList()
        } catch (error) {
          this.$message.error('操作失败,请重试')
        }
      } else {
        this.$message.info('已取消操作')
      }
    },

    // 删除
    async deleteQuestion(id) {
      const result = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (result === 'confirm') {
        const res = await deleteQuestionById({ id })
        console.log(res)
        this.$message.success('删除成功')
        if (this.choiceQuestionsList.length === 1 && this.queryData.page > 1) {
          this.queryData.page--
        }
        this.getChoiceQuestionsList()
        this.getChoiceQuestionsList()
      } else {
        this.$message.info('已取消删除')
      }
    },

    // 监听分页每页显示数量改变
    onpageSizeChange(val) {
      this.queryData.pagesize = val
      this.getChoiceQuestionsList()
    },
    // 监听当前点击的是哪一页
    onpageChange(val) {
      this.queryData.page = val
      this.getChoiceQuestionsList()
    },
    // 获取学科简单列表
    async getSimpleSubjects() {
      try {
        const { data } = await simpleSucjects({})
        this.subjectOptions = data
      } catch (error) {
        this.$message.error('获取学科列表信息失败,请稍后重试')
      }
    },
    // 学科下拉框选中项改变时触发
    onSubjectChange(subId) {
      this.queryData.catalogID = null
      this.queryData.tags = null
      this.getSimpleDirectorys(subId)
      this.getSimpleTags(subId)
    },
    // 获取目录简单列表
    async getSimpleDirectorys(id) {
      const { data } = await simpleDirectorys({ subjectID: id })
      this.directoryList = data
    },
    // 获取标签简单列表
    async getSimpleTags(id) {
      try {
        const { data } = await simpleTags({ subjectID: id })
        this.tagsList = data
      } catch (error) {
        this.$message.error('获取标签数据失败,请重试')
      }
    },
    // 获取用户列表(录入人)
    async getUserList() {
      try {
        const { data } = await userList({})
        this.userList = data.list
      } catch (error) {
        this.$message.error('获取录入人数据失败,请重试')
      }
    },
    // 城市下拉框选中项变化时
    onCityChange(val) {
      this.queryData.city = null
      this.areas = citys(val)
    },
    // 清除筛选条件
    clean() {
      this.queryData = {
        page: 1,
        pagesize: 5,
        subjectID: null, // 学科
        catalogID: null, // 目标
        tags: null, // 标签
        keyword: null, // 关键字
        questionType: '', //试题类型
        difficulty: '', // 难度
        direction: null, // 方向
        creatorID: null, // 录入人
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        province: null,
        city: null
      }
      this.directoryList = []
      this.tagsList = []
      this.areas = []
      this.getChoiceQuestionsList()
      this.getChoiceQuestionsList()
    },
    // 删除试题

    // 点击试题预览
    quesPreview(id) {
      this.quPrev.previewId = id
      this.quPrev.isPreviewShow = true
    }
  },
  computed: {},
  created() {
    this.getChoiceQuestionsList()
    this.getSimpleSubjects()
    this.getUserList()
  }
}
</script>

<style scoped lang="less">
.questions-choice-container {
  padding: 15px 10px;
  /deep/.el-card__header {
    border-bottom: 0;
    padding-bottom: 0;
  }

  .questionsSelectForm {
    /deep/.el-form-item__label {
      font-size: 14px;
    }
    .item-row {
      display: flex;

      .select-item {
        flex: 1;
        .el-select,
        .el-input {
          width: 100%;
        }
        .city {
          width: 49%;
          &:nth-child(1) {
            margin-right: 5px;
          }
        }
      }
      .cleanAndSearch {
        display: flex;
        justify-content: flex-end;
        align-items: flex-start;
        // .search-btn {
        //   margin-right: 31px;
        // }
      }
    }
  }

  .el-alert {
    margin-bottom: 15px;
  }
  .pageNation {
    margin-top: 15px;
  }

  /deep/.el-textarea__inner {
    margin-top: 25px;
  }
}
</style>
